package com.xunk.equipment.service.ruying;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.xunk.common.redis.service.RedisService;
import com.xunk.equipment.domain.EquipmentDO;
import com.xunk.equipment.domain.EquipmentPropertiesData;
import com.xunk.equipment.service.BaseService;
import com.xunk.equipment.service.IDimmingLightService;
import com.xunk.equipment.vo.response.DimmingLightInfoResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xunk.common.core.domain.EquipmentResponse;

import java.text.MessageFormat;
import java.util.*;
import java.util.function.BiFunction;

/**
 * @ProjectName: xunk
 * @Package: com.xunk.equipment.service.ruying
 * @ClassName: DimmingLightService
 * @Author: yangwendong
 * @Description:
 * @Date: 2021/4/1 10:47
 * @Version: 1.0
 */
@Slf4j
@Service("ruying-lightbulb")
public class DimmingLightService implements IDimmingLightService {

    @Autowired
    RedisService redisService;

    @Autowired
    BaseService baseService;

    @Autowired
    RuYingControlService ruYingControlService;

    private static final String on = "{0}.10.11";
    private static final String brightness = "{0}.10.12";
    private static final String colorTemperature = "{0}.10.13";
    private BiFunction<String, String, String> cmdFunction = (did, cmd) -> MessageFormat.format(cmd, did);

    //  硬件信息
    private static final String MODEL_ID = ".1.5";
    private static final String SERIAL_NUMBER_ID = ".1.7";
    private static final String FIRMWARE_REVISION_ID = ".1.2";

    @Override
    public EquipmentResponse getEquipmentInfo(EquipmentDO equipmentDO) {
        String deviceSn = equipmentDO.getDeviceSn();
        Long deptId = equipmentDO.getDeptId();
        Map<String, String> cacheMap = ruYingControlService.getShadowByDeviceSn(deviceSn, deptId);
        // 调光灯开关状态，pid = did.10.11 ,value值为true或者false
        String switchStateValue = cacheMap.getOrDefault(cmdFunction.apply(deviceSn, on), "false");

        // 调光灯的亮度 pid = did.10.12，value值为0-100之间步长为1的数
        String brightnessStateValue = cacheMap.get(cmdFunction.apply(deviceSn, brightness));

        // 调光灯的色温 pid = did.10.13,value值为2700-6500，步长为1
        String colorTemperatureStateValue = cacheMap.get(cmdFunction.apply(deviceSn, colorTemperature));

        DimmingLightInfoResponse response = new DimmingLightInfoResponse();
        response.setDeviceSn(deviceSn);
        response.setOn(Boolean.valueOf(switchStateValue));
        response.setBrightness(Optional.ofNullable(brightnessStateValue).map(Integer::valueOf).orElse(null));
        response.setColorTemperature(Optional.ofNullable(colorTemperatureStateValue).map(Integer::valueOf).orElse(null));
        response.setBrightnessRange(brightnessRange);
        response.setColorTemperatureRange(colorTemperatureRange);

        response.setModel(cacheMap.get(deviceSn.concat(MODEL_ID)));
        response.setFirmWare(cacheMap.get(deviceSn.concat(FIRMWARE_REVISION_ID)));
        response.setSerialNumber(cacheMap.get(deviceSn.concat(SERIAL_NUMBER_ID)));
        response.setSupplier(equipmentDO.getSupplier());
        response.setCandidateModel(baseService.getCandidateModel(equipmentDO.getDeviceBaseId()));
        return response;
    }

    private Map<String, Integer> brightnessRange = new HashMap<String, Integer>(3) {{
        put("min", 0);
        put("max", 100);
        put("step", 1);
    }};

    private Map<String, Integer> colorTemperatureRange = new HashMap<String, Integer>(3) {{
        put("min", 2700);
        put("max", 6500);
        put("step", 1);
    }};


    @Override
    public Boolean control(EquipmentDO equipmentDO, String type, String value) {
        // 查询当前设备对应的ownerId
        String deviceSn = equipmentDO.getDeviceSn();
        Long deptId = equipmentDO.getDeptId();
        String ownId = baseService.findOwnIdByDeptId(deptId);
        switch (type) {
            // 控制开关
            case "on":
                return controlOn(cmdFunction.apply(deviceSn, on), ownId, Boolean.valueOf(value));
            case "brightness":
                return controlOn(cmdFunction.apply(deviceSn, brightness), ownId, Integer.valueOf(value));
            case "colorTemperature":
                return controlOn(cmdFunction.apply(deviceSn, colorTemperature), ownId, Integer.valueOf(value));
            default:
                return null;
        }
    }

    private Boolean controlOn(String pid, String ownerId, Object value) {
        EquipmentPropertiesData data = new EquipmentPropertiesData();
        EquipmentPropertiesData.PropertyData propertyData = new EquipmentPropertiesData.PropertyData();
        propertyData.setPid(pid);
        propertyData.setValue(value);
        ArrayList<EquipmentPropertiesData.PropertyData> objects = Lists.newArrayList(propertyData);
        // 设置灯的时候，如果不是设置开和关的话，调节其他两个属性时，必须保证灯的打开状态
        if (!pid.contains(".10.11")) {
            String deviceSn = pid.split("\\.")[0];
            EquipmentPropertiesData.PropertyData propertyData1 = new EquipmentPropertiesData.PropertyData();
            propertyData1.setPid(deviceSn + ".10.11");
            propertyData1.setValue(true);
            objects.add(0, propertyData1);
            log.info("组合命令：{}", JSON.toJSONString(objects));
        }
        data.setProperties(objects);
        String s = ruYingControlService.setProperties(ownerId, data);
        return Objects.equals(s, "success");
    }
}
